package com.run.serial;

//import android.hardware.SerialPort;
import android.util.Log;

import androidx.annotation.NonNull;

import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

public final class SerialRxDataTask implements Runnable {
    private final String TAG = "RxDataThread";

    protected static long waitTime = 10;
    private SerialPort serialPort;

    private byte[] recvBuff = new byte[SerialCommand.RECEIVE_PACK_LEN_MAX];
    private ByteBuffer mInputBuffer = ByteBuffer.wrap(recvBuff);
    private int iDataLen;

    private InputStream mInputStream;

    protected SerialRxDataTask(@NonNull SerialPort port) {
        serialPort = port;
        mInputStream = serialPort.getInputStream();
    }

    @Override
    public void run() {
        try {
            while (SerialUtils.isReadData) {
                mInputBuffer.clear();
                iDataLen = mInputStream.read(recvBuff);
                byte[] buff = new byte[iDataLen];
                System.arraycopy(recvBuff, 0, buff, 0, iDataLen);
//                iDataLen = serialPort.read(mInputBuffer);
                if ( iDataLen > 0 ) {
                    Log.d("SerialRxDataTask",
                            "read >>  " + ConvertData.byteArrayToHexString(buff, iDataLen));

                    Log.d("SerialRxDataTask",
                            "read str>>:" + new String(buff, StandardCharsets.UTF_8) + ":end");

                    String ret = "";
                    if (new String(buff, StandardCharsets.UTF_8).equals("[OK]\n")
                            || new String(buff, StandardCharsets.UTF_8).contains("group")) {
                        Log.d("SerialRxDataTask",
                                "read str>>:" + new String(buff, StandardCharsets.UTF_8) + ":end");
                        ret = new String(SerialTxData.getInstance().reMoveUpClearQueue(), StandardCharsets.UTF_8);
                    }
                    SerialRxData.getInstance().rxDataPackage(ret, buff, iDataLen);
                }
                Thread.sleep(waitTime);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
